package com.game.sdk.floatwindow;

import java.util.HashMap;
import java.util.Map;

import android.text.TextUtils;
import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;

import com.game.sdk.YTAppService;
import com.game.sdk.domain.CloseWindowJavaScriptInterface;
import com.game.sdk.domain.ParamJson;
import com.game.sdk.domain.ResultCode;
import com.game.sdk.init.NetCallBack;
import com.game.sdk.pay.AndroidJSInterfaceForWeb;
import com.game.sdk.pay.ChargeActivityForWap;
import com.game.sdk.util.DataSafeUtil;
import com.game.sdk.util.DialogUtil;
import com.game.sdk.util.Encrypt;
import com.game.sdk.util.GetDataImpl;
import com.game.sdk.util.Logger;
import com.game.sdk.util.MResource;
import com.game.sdk.util.Md5Util;
import com.game.sdk.util.NetworkImpl;
import com.game.sdk.util.Util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class FloatWebActivity extends Activity implements OnClickListener {
	private static final String TAG = "FloatWebActivity";
	private WebView wv;
	private TextView tv_back, tv_charge_title;
	private ImageView iv_cancel;
	private String url, title;
	private String appid, username, memkey;
	private StringBuffer postDate = new StringBuffer("");

	private boolean clickable = true;
	private ParamJson params;
	private String type;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(MResource.getIdByName(getApplication(), "layout",
				"sdk_float_web"));

		// findViewById(MResource.getIdByName(getApplication(), "id",
		// "iv_ingame"))
		// .setOnClickListener(this);// 进入游戏
		Intent intent = getIntent();
		url = intent.getStringExtra("url");
		title = intent.getStringExtra("title");
		appid = intent.getStringExtra("appid");
		params = (ParamJson) intent.getSerializableExtra("params");
		type = intent.getStringExtra("type");

		username = intent.getStringExtra("username");
		memkey = intent.getStringExtra("memkey");
		if (TextUtils.isEmpty(GetDataImpl.PHPSESSID)) {
			Toast.makeText(this, "还没有初始化sdk", 0).show();
			this.finish();
		}
//		 String sign = Md5Util.md5(appid + "##" + username + "##" + memkey);
//				 postDate.append("appid=").append(appid).append("&username=")
//				 .append(username).append("&sign=").append(sign);
		wv = (WebView) findViewById(MResource.getIdByName(getApplication(),
				"id", "wv_content"));
		tv_back = (TextView) findViewById(MResource.getIdByName(
				getApplication(), "id", "tv_back"));
		iv_cancel = (ImageView) findViewById(MResource.getIdByName(
				getApplication(), "id", "iv_cancel"));

		tv_charge_title = (TextView) findViewById(MResource.getIdByName(
				getApplication(), "id", "tv_charge_title"));
		tv_charge_title.setText(title);
		tv_back.setOnClickListener(this);
		iv_cancel.setOnClickListener(this);
		final Map<String, String> header = new HashMap<String, String>();
		header.put("Cookie", "HUOSHUID=" + GetDataImpl.PHPSESSID);

		String token = "";
		token = YTAppService.userinfo == null ? "" : TextUtils
				.isEmpty(YTAppService.userinfo.user_token) ? ""
				: YTAppService.userinfo.user_token;
//		url = url + "?user_token=" +token
//				+ "&param_token="
//				+ Util.getTokenForFloat(token);
		if(TextUtils.isEmpty(GetDataImpl.PHPSESSID)||"null".equals(GetDataImpl.PHPSESSID)||"NULL".equals(GetDataImpl.PHPSESSID)){
			Toast.makeText(this, "网络异常，请重新登录", 0).show();
			this.finish();
			return;
		}
		postDate.append("user_token=").append(token).append("&param_token=")
		.append(Util.getTokenForFloat(token)).append("&session_id=").append(GetDataImpl.PHPSESSID);
		wv.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				wv.postUrl(url, EncodingUtils.getBytes(postDate.toString(), "UTF-8"));
				return true;
			}
		});

		wv.getSettings().setJavaScriptEnabled(true);
		wv.getSettings().setLoadsImagesAutomatically(true);
		wv.getSettings().setAppCacheEnabled(false);
		wv.getSettings().setDomStorageEnabled(true);
		wv.getSettings().setDefaultTextEncodingName("UTF-8");
		AndroidJSInterfaceForWeb closejs = new AndroidJSInterfaceForWeb();
		closejs.ctx = this;
		wv.addJavascriptInterface(closejs, "ttw_w");

		wv.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				if (!DialogUtil.isShowing()) {
					DialogUtil.showDialog(FloatWebActivity.this, "正在加载...");
				}
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				webviewCompat(wv);
				try {
					DialogUtil.dismissDialog();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});
		webviewCompat(wv);
		wv.setWebChromeClient(new WebChromeClient());
	    wv.postUrl(url, EncodingUtils.getBytes(postDate.toString(), "UTF-8"));
//		wv.loadUrl(url, header);

	}

	public String getUrl(String url) {
		url = url + "?user_token=" + YTAppService.userinfo.user_token
				+ "&param_token="
				+ Util.getTokenForFloat(YTAppService.userinfo.user_token);
		return url;
	}

	@Override
	public void onClick(View v) {
		
		if (v.getId() == tv_back.getId()) {
			if (!wv.canGoBack()) {
				if (title.equals("忘记密码")) {
					FloatViewImpl.getInstance(this);
					FloatViewImpl.removeFloat();
					this.finish();
				} else {
					FloatViewImpl.getInstance(this);
					FloatViewImpl.ShowFloat();
					this.finish();
				}
			} else {
				// 返回的时候web端 出现异常，可能需要改成退出界面 @author ling
				wv.goBack();// 返回前一个页面
				wv.getSettings().setCacheMode(
						WebSettings.LOAD_CACHE_ELSE_NETWORK);
			}
		}
		if (v.getId() == iv_cancel.getId()) {
			if (title.equals("忘记密码")) {
				FloatViewImpl.getInstance(this);
				FloatViewImpl.removeFloat();
				this.finish();
			} else {
				FloatViewImpl.getInstance(this);
				FloatViewImpl.ShowFloat();
				this.finish();
			}
		}

	}

	public String parseUserData(ParamJson paraString) {
		// //StringBuffer postDate = new StringBuffer("");
		// postDate.append("a=").append(paraString.getAppid()).append("&c=").append(paraString.getImei());
		// postDate.append("&d=").append(paraString.getFrom()).append("&e=").append(paraString.getAgentgame());
		// postDate.append("&f=").append(paraString.getDeviceinfo()).append("&g=").append(paraString.getUserua());
		// postDate.append("&v=").append(paraString.getUserid()).append("&w=").append(paraString.getCode());
		// postDate.append("&x=").append(paraString.getClient_id()).append("&y=").append(paraString.getApi_token());
		// postDate.append("&z=").append(paraString.getUser_token()).append("&az=").append(paraString.getParams_key());
		// postDate.append("&ac=").append(paraString.getIpaddrid());
		return paraString.getAllString();
	}

	/**
	 * 一些版本特性操作，需要适配、
	 * 
	 * @date 6/3
	 * @param mWebView
	 * @reason 在微蓝项目的时候遇到了 返回键 之后 wv显示错误信息
	 * */
	private void webviewCompat(WebView mWebView) {
		if (NetworkImpl.isNetWorkConneted(mWebView.getContext())) {
			mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
		} else {
			mWebView.getSettings().setCacheMode(
					WebSettings.LOAD_CACHE_ELSE_NETWORK);
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && wv.canGoBack()) {
			wv.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
			wv.goBack();// 返回前一个页面
			return true;
		}
		if (title.equals("忘记密码")) {
			FloatViewImpl.getInstance(this);
			FloatViewImpl.removeFloat();
			return super.onKeyUp(keyCode, event);
		} else {
			FloatViewImpl.getInstance(this);
			FloatViewImpl.ShowFloat();
			return super.onKeyUp(keyCode, event);
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		this.finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.finish();
	}
	private Handler mHandler = new Handler();
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ChargeActivityForWap.REQUEST_CODE) {
			if (data != null) {
				double amount = data.getDoubleExtra("amount", 0);
				boolean sus = data.getBooleanExtra("result", false);
				String toast = data.getStringExtra("attach");
				if(sus){
					if(wv.canGoBack()){
						wv.goBack();
					}
					Toast.makeText(this, "充值成功", Toast.LENGTH_LONG).show();
				}
				mHandler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						wv.reload();
					}
				}, 120);
				
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
